package com.mingqijia.gassafety.authority.vcc.provider;

import com.mingqijia.gassafety.authority.api.resp.manager.UserProfileRespDTO;
import com.mingqijia.gassafety.authority.dal.provider.CompanyProvider;
import com.mingqijia.gassafety.authority.domain.adapter.BenAdapter;
import com.mingqijia.gassafety.db.entity.auth.CompanyEntry;
import com.mingqijia.gassafety.shared.enums.RunningState;
import com.mingqijia.gassafety.shared.enums.YesNoEnum;
import com.mingqijia.gassafety.shared.utils.ApplicationUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

@Slf4j
@Component
@RequiredArgsConstructor
public class VccCompanyOrgMatcher implements ApplicationListener<OrgMatchEvent> {

    private final CompanyProvider provider;
    private final BenAdapter adapter;

    @Override
    public void onApplicationEvent(OrgMatchEvent event) {
        if (!(event.getPayload() instanceof UserProfileRespDTO)) {
            return;
        }
        syncOrgCode((UserProfileRespDTO)event.getPayload());
    }

    private void syncOrgCode(UserProfileRespDTO profile) {
        if (CollectionUtils.isEmpty(profile.getAuthorizedSp())) {
            return;
        }
        profile.getAuthorizedSp().forEach(resp -> {
            CompanyEntry entry = provider.getById(resp.getId());
            if (!ObjectUtils.isEmpty(entry)) {
                adapter.updateCompanyDepart(entry);
                return;
            }
            entry = CompanyEntry.builder().id(resp.getId()).code(resp.getCode()).source(1)
                    .name(resp.getName()).alias(resp.getName()).isDeleted(YesNoEnum.N.isFlag())
                    .state(RunningState.RUNNING.getCode()).spId(profile.getWorkingSpId())
                    .createdBy(ApplicationUtils.getWorkingUser().getUsername()).build();
            try {
                provider.save(entry);
            } catch (Exception e) {
                log.error("保存企业失败[spid={},code={}]",resp.getId(), resp.getCode(),e);
            }
        });
    }
}
